Python Scripting Language

Basic Syntax

  • arithmatic operators: +, -, *, /, **, %, ==, ...
  • variable and symbolic operation: By famous sympy package;
  • define function: input var1, pass x to var2 if no var2 input, and return result ,
    def func(var1,var2=x):
        ...
        return result
  • condition statments
    if cond1: 
          ...
       elif cond2:
          ...
       else:
          ...
  • while statement:
     while( condition):
        ...
  • for statement:
    for (...):
     ...
In [ ]:
a=5;b=9
print(a+b,a-b,a*b,a/b)
In [ ]:
print("sum = %s,difference = %s,product = %s, quotient= %s" %(a+b,a-b,a*b,a/b))
In [ ]:
def iseven(x):
    return x%2==0

iseven(798)
In [ ]:
def tax(x):
    if x<680000.:
        print( "Tax is 0.")
    elif x<1200000:
        print("Tax is %g" %float(x*0.06-22800))
    else:
        print("TeX is %s" % float(x*0.12-136000))
In [ ]:
tax(1000000)
In [ ]:
# add time module to sum a sequence of consecutive integers 
import time
sum=0
n=10000000

t0=time.time()
for i in range(n+1):
    sum+=i
print(time.time()-t0)
print ("Summation of consecutive natual numbers from 1 to %d is %d." %(n,sum))

NumPy: core of Scientific Computing

It contains among other things:

* a powerful N-dimensional array object
* sophisticated (broadcasting) functions
* tools for integrating C/C++ and Fortran code
* useful linear algebra, random number capabilities,  and Fourier transform.

Import Packages

  • import numPy: prepare numpt to use;
    import numpy 
    numpy.sin(numpy.pi)
    get 0
  • import numpy as numpy: give the nicknme
    import numpy as np
    np.sin(np.pi)
    get 0
  • from numpy import *: import all the staff into Python environment, not prefered:
    import numpy 
    sin(pi)
    get 0
  • from numpy import sin: import only one numpy function, sin:
    import numpy  as np
    from numpy import sin
    sin(np.pi)
    get 0
In [ ]:
import numpy as np
import time
sum=0
n=10000000

t0=time.time()
a=np.linspace(0,n,n+1)
sum=np.sum(a)
print(time.time()-t0)
print ('Summation of consecutive natual numbers from 1 to %d is %d.' %(n,sum))

Exercise

What is the 10000 term of Fibonicci sequence?

Moreover

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined and this allows NumPy to seamlessly and speedily integrate with a wide variety of projects.

Matplotlib

Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures. Some of the many advantages of this library include:

  • Easy to get started
  • Support for $\LaTeX$ formatted labels and texts
  • Great control of every element in a figure, including figure size and DPI.
  • High-quality output in many formats, including PNG, PDF, SVG, EPS, and PGF.
  • GUI for interactively exploring figures and support for headless generation of figure files (useful for batch jobs).

One of the of the key features of matplotlib that I would like to emphasize, and that I think makes matplotlib highly suitable for generating figures for scientific publications is that all aspects of the figure can be controlled programmatically. This is important for reproducibility and convenient when one needs to regenerate the figure with updated data or change its appearance.

More information at the Matplotlib web page: http://matplotlib.org/

Matlab-like API's

The easiest way to get started with plotting using matplotlib is often to use the MATLAB-like API provided by matplotlib.

It is designed to be compatible with MATLAB's plotting functions, so it is easy to get started with if you are familiar with MATLAB.

To use this API from matplotlib, we need to include the symbols in the pylab module:

Animation

Matplotlib also includes a simple API for generating animations for sequences of figures. With the FuncAnimation function we can generate a movie file from sequences of figures. The function takes the following arguments: fig, a figure canvas, func, a function that we provide which updates the figure, init_func, a function we provide to setup the figure, frame, the number of frames to generate, and blit, which tells the animation function to only update parts of the frame which have changed (for smoother animations):

def init():
    # setup figure

def update(frame_counter):
    # update figure for new frame

anim = animation.FuncAnimation(fig, update, init_func=init, frames=200, blit=True)

The functionality, animation, works like a chant within IPython notebook with JSAnimation.

The matplotlib object-oriented API

The main idea with object-oriented programming is to have objects that one can apply functions and actions on, and no object or program states should be global (such as the MATLAB-like API). The real advantage of this approach becomes apparent when more than one figure is created, or when a figure contains more than one subplot.

To use the object-oriented API we start out very much like in the previous example, but instead of creating a new global figure instance we store a reference to the newly created figure instance in the fig variable, and from it we create a new axis instance axes using the add_axes method in the Figure class instance fig:

In [5]:
# the following "matplotlib" magic  actives the embedded function if any picture created. 
%matplotlib inline
import pylab as plt
import numpy as np
from numpy import sin,cos,pi

x=np.linspace(-2,2,1000)
f=x*np.sin(1/x)
plt.plot(x,f)
Out[5]:
[<matplotlib.lines.Line2D at 0x10840bc88>]
In [6]:
g=np.sin(x)
plt.plot(x,f,'r-',x,g,'b--',lw=2)
Out[6]:
[<matplotlib.lines.Line2D at 0x1085134a8>,
 <matplotlib.lines.Line2D at 0x108513668>]
In [7]:
x=np.linspace(0,2*np.pi,100)
plt.polar(x,1+sin(x))+plt.polar(x,2-3*sin(x))
Out[7]:
[<matplotlib.lines.Line2D at 0x108636a58>,
 <matplotlib.lines.Line2D at 0x108638cf8>]
In [8]:
from numpy import sin,cos,pi,ones
x=np.linspace(0,2*np.pi,100)
plt.polar(x,1.8+sin(x)+sin(3*x)/3.,lw=4)+ plt.polar(x,2.2*cos(x)+2*sin(x),lw=6,color="red") \
   + plt.polar(x,-2.2*cos(x)+2*sin(x), lw=6,color="red") + plt.polar(x[55:-5],2*ones(40),lw=8)
Out[8]:
[<matplotlib.lines.Line2D at 0x108745f28>,
 <matplotlib.lines.Line2D at 0x108518160>,
 <matplotlib.lines.Line2D at 0x108748be0>,
 <matplotlib.lines.Line2D at 0x108748d68>]
In [9]:
plt.figure(figsize=(4,4))
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)

x=np.linspace(0,2*np.pi,200)

plt.plot(cos(5*x),sin(8*x))
Out[9]:
[<matplotlib.lines.Line2D at 0x10875afd0>]
In [10]:
# Arrar of pictures
plt.figure(figsize=(4,4))
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)

x=np.linspace(0,2*np.pi,200)

[plt.plot(cos(3*x),sin(i*x)) for i in np.arange(5)];
In [11]:
import matplotlib.pylab as plt
from matplotlib import animation
from JSAnimation import IPython_display
from numpy import sin,cos,pi
In [12]:
x1,x2,y1,y2=0,1,0,1
t1=365.256   # one year for Earth 
t2=224.701   # one year for Venus
R1=149.6     # 1,000,000 km distance between Earth and Sun
R2=108.21    # 1,000,000 km distance between Venus and Sun
Ratio=R1/R2

def CartesianE(n,  R=Ratio):
    x=[]
    theta= 8*2*pi/t1;
    for i in range(n):
        x += [R*cos(i*theta),R*sin(i*theta)]
    return x

def CartesianV(n,  R=1):
    x=[]
    theta= 8*2*pi/t2;
    for i in range(n):
        x += [R*cos(i*theta),R*sin(i*theta)]
    return x
    
days=7
n=100

ob= n*days

P=CartesianE(ob)
Q=CartesianV(ob)
In [13]:
k=20
anim=plt.figure(figsize=(8,8));
ax = anim.add_subplot(111)
plt.title("La Vie en Rose",fontsize=14);

plt.ylim([-1.5,1.5]);
plt.xlim([-1.5,1.5]);
def init():
    return  plt.plot([P[0],Q[0]],[P[1],Q[1]], color='0.2');

PP=[[P[2*k],Q[2*k]] for k in np.arange(100)];
QQ=[[P[2*k+1],Q[2*k+1]] for k in np.arange(100)];
def animate(i):
    return [ax.plot(PP[k],QQ[k],color='0.2') for k in np.arange(i)];

animation.FuncAnimation(anim, animate, init_func=init,frames=100)   
Out[13]:


Once Loop Reflect
In [ ]:
 

How comes Rose

Eight Earth years is approximated to thirteen Venus ywars:

In [ ]:
print(t1*8, t2*13)

D3 binging

Benefit from the javascript library, d3.js, experimental mpld3 avails the visualization functionalities and pythreejs.js:

1. Jupyter Settings

Not only come the directly Python packages, but Jupyter allows user to bridge the utility in platform to work much flexibly:

In [ ]:
# 1. Jupyter path
!jupyter --paths
In [ ]:
 

2. nbextensions

Enchancement for Jupyter notebook interface:

for instance, we want to install pythreejs, A Python / ThreeJS bridge utilizing the Jupyter widget infrastructure:

shell > pip install pythreejs
shell > jupyter nbextension enable --py pythreejs

Then check the nbextension setting, it should be included in system, such as

shell > jupyter nbextension list
    ...
    jupyter-threejs/extension  enabled 
      - Validating: OK
    ...

above shows it's join okay.

In [4]:
!jupyter nbconvert introduction.ipynb
[NbConvertApp] Converting notebook introduction.ipynb to html
[NbConvertApp] Writing 289896 bytes to introduction.html
In [ ]: